﻿using System.Linq;
using System.Web;
using Whoever.Framework.Utils;
using Whoever.Framework.Enum;
using Whoever.Framework.CustomException;

using Whoever.Patterns.Business;

using EditorialProyectos.DataAccess.Repositories;
using EditorialProyectos.Business.Entities;

namespace EditorialProyectos.Business
{
    public class UserManager : Manager<User>
    {
        public UserManager()
            : base(RepositoryFactory.UserRepository)
        {

        }

        public bool HavePermission(User user, string controllerName, string actionName)
        {
            UserRepository userRepository = new UserRepository();
            return userRepository.HavePermission(user, controllerName, actionName);
        }

        public User Login(User user)
        {
            user = ResolveAccessMethod(user);
            user = AttemptLogin(user);

            if (user != null)
            {
                Repository.Update(user);
                return user;
            }

            throw new BusinessException(Localized.Message("Login", MessageType.Error));
        }
        
        protected User ResolveAccessMethod(User user)
        {
            if (user.Account.IndexOf('@') != -1)
            {
                user.Email = user.Account;
                user.Account = string.Empty;
            }
            return user;
        }

        protected User AttemptLogin(User user)
        {
            var realUser = new User();

            if (!string.IsNullOrEmpty(user.Account))
                realUser = Repository.GetAll().SingleOrDefault(e => Equals(e.Account.ToUpper(), user.Account.ToUpper()));

            if (!string.IsNullOrEmpty(user.Email))
                realUser = Repository.GetAll().SingleOrDefault(e => Equals(e.Email.ToUpper(), user.Email.ToUpper()));

            if (realUser != null)
                //Case sensitive password
                if (Cryptography.Decrypt(realUser.Password) == user.Password)
                {
                    user = realUser;
                }
                else
                    user = null;

            return user;
        }

        public bool AccountExists(string account)
        {
            return this.Repository.QueryFactory.GetAll().SingleOrDefault(x => x.Account == account) != null;
        }
    }
}
